/** @format */

import { resultsModel } from '../../../sdk'
import { CODE_TYPES } from '../../../errorCode'
import { dbFindOne } from '../mongodb'
import { TASK_DB_NAME, USER_DB_NAME } from '../../../db'
import { GAME_TYPE } from '../../../constants';


/**
 *  检查inviteId是否合法 返回邀请人的用户信息
 *
 * @export
 * @param {IContext<{ activityId: string; inviteId: string }>} context
 * @return {*}
 */
export default async function checkInviteId(
  context: IContext<IParams>,
  { activityInfo }: IControllerInfos
) {
  const {
    openId,
    data: { pageId, inviteId }
  } = context

  const { type: taskType, taskLimit, game } = context.data

  // 不是邀请不校验
  if (taskType !== 'shareForHelp') return

  // 自己邀请自己
  if (openId === inviteId) return resultsModel.error(CODE_TYPES.ERROR_NO_INVITE_SELF)

  // 获取邀请者信息
  const inviteUserInfo = await dbFindOne<IUserInfo>(context, USER_DB_NAME, {
    pageId,
    openId: inviteId
  })

  // inviteId的用户信息查询不到, 则inviteId无效
  if (!inviteUserInfo) return resultsModel.error(CODE_TYPES.ERROR_NO_INVITEID)

  // 好友今日任务次数
  const { todayLotTaskCompleteTimes, todayBlessTaskCompleteTimes } = inviteUserInfo;
  const completeTotal = GAME_TYPE.DRAW_LOTS === game ? todayLotTaskCompleteTimes : todayBlessTaskCompleteTimes
  if (completeTotal >= +taskLimit) {
    return resultsModel.error(CODE_TYPES.ERROR_TASK_LIMIT, '好友今日任务总【领取】次数已达上限');
  }

  // 助力信息
  const doHelpInfo = await dbFindOne<ITaskInfo>(context, TASK_DB_NAME, {
    pageId,
    openId: inviteId,
    beInviteId: openId,
    type: taskType,
    game
  })

  if (doHelpInfo) {
    return resultsModel.error(CODE_TYPES.ERROR_AREADY_INVITE_SUCCESS);
  }

  return {
    inviteUserInfo
  }
}
